import json
import os

WE_CHAT_TARGETS_FILE = "wechat_targets.json"

def bind_wechat():
    try:
        # 确保COM库已初始化
        import win32com.client
        win32com.client.gencache.EnsureDispatch('Word.Application')
        
        pythoncom.CoInitialize()
        wx = WeChat()
        
        # 增加重试机制和超时处理
        for i in range(3):
            try:
                wx.GetSessionList()  # 尝试获取会话列表来验证绑定
                print("微信绑定成功")
                return wx
            except Exception as e:
                if i == 2:  # 最后一次尝试失败
                    raise
                time.sleep(1)  # 等待1秒后重试
    except Exception as e:
        print(f"微信绑定失败: {e}")
        print("请确保：")
        print("1. 微信PC版已登录并保持在前台")
        print("2. 已安装Windows Update KB971513")
        print("3. 尝试重新启动微信和本程序")
        return None

def save_wechat_targets(targets):
    """保存微信目标到文件"""
    try:
        with open(WE_CHAT_TARGETS_FILE, 'w', encoding='utf-8') as f:
            json.dump(targets, f, ensure_ascii=False, indent=2)
    except Exception as e:
        print(f"保存微信目标失败: {e}")

def load_wechat_targets():
    """从文件加载微信目标"""
    try:
        if os.path.exists(WE_CHAT_TARGETS_FILE):
            with open(WE_CHAT_TARGETS_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
    except Exception as e:
        print(f"加载微信目标失败: {e}")
    return {"friends": [], "groups": []}

try:
    from wxauto import WeChat
    import pythoncom
    
    def bind_wechat():
        try:
            # 初始化COM库
            pythoncom.CoInitialize()
            
            wx = WeChat()
            # 增加重试机制
            for i in range(3):
                try:
                    wx.GetSessionList()  # 尝试获取会话列表来验证绑定
                    print("微信绑定成功")
                    return wx
                except Exception as e:
                    if i == 2:  # 最后一次尝试失败
                        raise
                    time.sleep(1)  # 等待1秒后重试
        except Exception as e:
            print(f"微信绑定失败: {e}")
            print("请确保：")
            print("1. 微信PC版已登录并保持在前台")
            print("2. 已安装Windows Update KB971513")
            print("3. 尝试重新启动微信和本程序")
            return None

    def send_wechat_message(wx, target_name, message, is_group=False):
        """发送微信消息"""
        try:
            # 检查目标名称是否有效
            if not target_name or not isinstance(target_name, str):
                print(f"微信提醒: 无效的目标名称: {target_name}")
                return False
                
            # 获取当前会话列表
            sessions = wx.GetSessionList()
            if not sessions:
                print("微信提醒: 无法获取会话列表")
                return False
                
            # 查找目标会话
            target_found = any(target_name in session for session in sessions)
            if not target_found:
                print(f"微信提醒: 未找到目标联系人/群组: {target_name}")
                return False
                
            # 发送消息
            if is_group:
                wx.ChatWith(target_name)  # 切换到群聊
            else:
                wx.ChatWith(target_name)  # 切换到好友
            wx.SendMsg(message)
            return True
            
        except IndexError:
            print(f"微信提醒: 目标联系人不存在: {target_name}")
            return False
        except Exception as e:
            print(f"微信提醒: 发送消息时出错: {str(e)}")
            return False
except ImportError:
    print("未找到 wxauto 库，请先安装。")
    # 为了避免导入错误，这里可以定义空函数
    def bind_wechat():
        print("请先安装 wxauto 库")
        return None
        
    def send_wechat_message(wx, target_name, message, is_group=False):
        print("请先安装 wxauto 库")
        return False
